# -*- coding: utf-8 -*-
"""
@Project ：weather 
@File    ：weather_splicing.py
@Author: guzain
@Date:  2025/7/7 11:32:29
@Email： GZA5210@163.com
@Description: 天气数据拼接模块
"""
from utils.log_config import logger
from services.quotes import Get_dailyEnglish, Get_love, Get_wyy
from services.weather_info import Get_city_from_ip
from services.weather_data import Get_today_Weather, Get_tomorrow_Weather
from services.weather_constants import local_time


def Splicing_text_data(music_content, music_name, lz_ch, lz_en, love):
    """拼接文本格式的天气数据
    Args:
        music_content: 网易云音乐热评内容
        music_name: 网易云音乐歌曲名
        lz_ch: 每日英语中文内容
        lz_en: 每日英语英文内容
        love: 爱情语录内容
    Returns:
        拼接后的文本天气数据
    """
    try:
        # 直接使用传入的各类数据，不再内部调用
        # 从weather_info模块获取城市信息，该模块已经处理了USE_NETWORK_CITY配置
        from services.weather_info import city
        
        # 初始化默认值，防止None值导致错误
        if lz_ch is None:
            lz_ch = ""
        if lz_en is None:
            lz_en = ""
        if love is None:
            love = ""
        if city is None:
            city = ""
        if music_content is None:
            music_content = ""
        if music_name is None:
            music_name = ""
        
        # 根据时间获取相应的天气数据
        if 0 <= local_time < 18:  # 白天
            today_weather_data = Get_today_Weather()
            if today_weather_data:
                # 构建今天的天气文本
                today_text = (
                    f'{city}天气：\n'
                    f'现在天气：{today_weather_data["weather_text"]}\n\n'
                    f'{today_weather_data["weather_text_str"]}\n\n'
                    f'当前温度：{today_weather_data["weather_temp"]}°C\n\n'
                    f'当前体感温度：{today_weather_data["weather_feels_like"]}°C\n\n'
                    f'湿度：{today_weather_data["humidity"]}%\n\n'
                    f'最高温度：{today_weather_data["temp_high"]}  '
                    f'最低温度：{today_weather_data["temp_low"]}\n\n'
                    f'日出时间：{today_weather_data["sunrise"]} 🌄'
                    f'   日落时间：{today_weather_data["sunset"]} 🌄\n\n'
                    f'{today_weather_data["uv_index_str"]}\n\n'
                    f'{today_weather_data["today_text_str"]}\n\n'
                    f'励志一句：{lz_ch}\n\n{lz_en}\n\n'
                    f'我想对你说：{love}\n\n'
                    f'网易云音乐热评：{music_content}—{music_name}'
                )
                return today_text
            else:
                return "获取今天天气数据失败！"
        elif 19 <= local_time <= 23:  # 晚上七点后
            tomorrow_weather_data = Get_tomorrow_Weather()
            if tomorrow_weather_data:
                # 构建明天的天气文本
                tomorrow_text = (
                    f'{city}天气：\n'
                    f'{tomorrow_weather_data["date"]}\n\n'
                    f'明天天气：{tomorrow_weather_data["text"]}\n\n'
                    f'最高温度：{tomorrow_weather_data["temp_high"]}°C\n\n'
                    f'最低温度：{tomorrow_weather_data["temp_low"]}°C\n\n'
                    f'湿度：{tomorrow_weather_data["humidity"]}%\n\n'
                    f'紫外线强度：{tomorrow_weather_data["uv_index"]}\n\n'
                    f'日出时间：{tomorrow_weather_data["sunrise"]}🌄'
                    f'  日落时间{tomorrow_weather_data["sunset"]}🌇\n\n'
                    f'{tomorrow_weather_data["weather_text_str"]}'
                    f'励志一句：{lz_ch}\n\n{lz_en}\n\n'
                    f'我想对你说：{love}\n\n'
                    f'网易云音乐热评：{music_content}—{music_name}'
                )
                return tomorrow_text
            else:
                return "获取明天天气数据失败！"
        else:
            return "当前时间不在推送范围内"
    except Exception as e:
        logger.error(f"生成天气数据失败：{e}", exc_info=True)
        return f"生成天气数据失败：{e}"


def get_weather_icon(weather_text):
    """根据天气文本获取对应的天气图标
    Args:
        weather_text: 天气文本，如"晴"、"多云"等
    Returns:
        天气图标emoji
    """
    weather_icon_map = {
        "晴": "☀️",
        "多云": "⛅",
        "阴": "☁️",
        "小雨": "🌧️",
        "中雨": "🌧️",
        "大雨": "⛈️",
        "暴雨": "⛈️",
        "雷阵雨": "⛈️",
        "小雪": "❄️",
        "中雪": "❄️",
        "大雪": "❄️",
        "雾": "🌫️",
        "霾": "🌫️",
        "沙尘": "🌪️",
        "大风": "💨"
    }
    # 遍历天气图标映射，找到匹配的图标
    for key, icon in weather_icon_map.items():
        if key in weather_text:
            return icon
    return "🌤️"  # 默认图标


def Splicing_html_data(music_content, music_name, lz_ch, lz_en, love):
    """拼接HTML格式的天气数据，用于邮件发送
    Args:
        music_content: 网易云音乐热评内容
        music_name: 网易云音乐歌曲名
        lz_ch: 每日英语中文内容
        lz_en: 每日英语英文内容
        love: 爱情语录内容
    Returns:
        拼接后的HTML天气数据
    """
    try:
        # 动态获取当前时间（小时）
        import datetime
        import time
        import pytz
        import os
        
        cur_time = time.time()
        local_tz = pytz.timezone("Asia/Shanghai")
        local_time = datetime.datetime.fromtimestamp(cur_time, tz=local_tz).hour
        
        # 直接使用传入的各类数据，不再内部调用
        # 从weather_info模块获取城市信息，该模块已经处理了USE_NETWORK_CITY配置
        from services.weather_info import city
        
        # 初始化默认值，防止None值导致错误
        if lz_ch is None:
            lz_ch = ""
        if lz_en is None:
            lz_en = ""
        if love is None:
            love = ""
        if city is None:
            city = ""
        if music_content is None:
            music_content = ""
        if music_name is None:
            music_name = ""
        
        # 读取HTML模板文件
        template_path = os.path.join(os.path.dirname(__file__), 'weather_template.html')
        with open(template_path, 'r', encoding='utf-8') as f:
            html_template = f.read()
        
        # 根据时间获取相应的天气数据，生成动态天气内容
        weather_content = ""
        if 0 <= local_time < 19:  # 白天（0点到19点前）
            today_weather_data = Get_today_Weather()
            if today_weather_data:
                weather_icon = get_weather_icon(today_weather_data['weather_text'])
                # 生成今天的天气HTML内容
                weather_content = f"""
                    <div class="weather-card">
                        <h3>今日天气</h3>
                        
                        <div class="weather-overview">
                            <div class="weather-main">
                                <div class="weather-icon">{weather_icon}</div>
                                <div>
                                    <div class="weather-temp">{today_weather_data['weather_temp']}°C</div>
                                    <div class="weather-text">{today_weather_data['weather_text']}</div>
                                </div>
                            </div>
                            <div class="weather-status">
                                <p>体感温度: {today_weather_data['weather_feels_like']}°C</p>
                                <p>湿度: {today_weather_data['humidity']}%</p>
                            </div>
                        </div>
                        
                        <div class="weather-details">
                            <div class="detail-item">
                                <div class="detail-label">最高温度</div>
                                <div class="detail-value">{today_weather_data['temp_high']}<span class="detail-unit">°C</span></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">最低温度</div>
                                <div class="detail-value">{today_weather_data['temp_low']}<span class="detail-unit">°C</span></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">紫外线</div>
                                <div class="detail-value">{today_weather_data['uv_index']}</div>
                            </div>
                        </div>
                        
                        <div class="sun-info">
                            <div class="sun-item">
                                <span class="sun-icon">🌅</span>
                                <div class="sun-label">日出时间</div>
                                <div class="sun-time">{today_weather_data['sunrise']}</div>
                            </div>
                            <div class="sun-item">
                                <span class="sun-icon">🌇</span>
                                <div class="sun-label">日落时间</div>
                                <div class="sun-time">{today_weather_data['sunset']}</div>
                            </div>
                        </div>
                        
                        <div class="weather-tip">
                            {today_weather_data['weather_text_str']}{today_weather_data['today_text_str']}{today_weather_data['uv_index_str']}
                        </div>
                    </div>
                """
        else:  # 19点后显示明天天气
            tomorrow_weather_data = Get_tomorrow_Weather()
            if tomorrow_weather_data:
                weather_icon = get_weather_icon(tomorrow_weather_data['text'])
                # 生成明天的天气HTML内容
                weather_content = f"""
                    <div class="weather-card">
                        <h3>明日天气</h3>
                        
                        <div class="weather-overview">
                            <div class="weather-main">
                                <div class="weather-icon">{weather_icon}</div>
                                <div>
                                    <div class="weather-text">{tomorrow_weather_data['text']}</div>
                                    <div class="weather-temp">{tomorrow_weather_data['temp_low']}°C ~ {tomorrow_weather_data['temp_high']}°C</div>
                                </div>
                            </div>
                            <div class="weather-status">
                                <p>湿度: {tomorrow_weather_data['humidity']}%</p>
                                <p>紫外线: {tomorrow_weather_data['uv_index']}</p>
                            </div>
                        </div>
                        
                        <div class="sun-info">
                            <div class="sun-item">
                                <span class="sun-icon">🌅</span>
                                <div class="sun-label">日出时间</div>
                                <div class="sun-time">{tomorrow_weather_data['sunrise']}</div>
                            </div>
                            <div class="sun-item">
                                <span class="sun-icon">🌇</span>
                                <div class="sun-label">日落时间</div>
                                <div class="sun-time">{tomorrow_weather_data['sunset']}</div>
                            </div>
                        </div>
                        
                        <div class="weather-tip">
                            {tomorrow_weather_data['weather_text_str']}
                        </div>
                    </div>
                """
        
        # 替换HTML模板中的所有占位符
        html_content = html_template.replace('{city}', city)
        html_content = html_content.replace('{weather_content}', weather_content)
        html_content = html_content.replace('{lz_ch}', lz_ch)
        html_content = html_content.replace('{lz_en}', lz_en)
        html_content = html_content.replace('{love}', love)
        html_content = html_content.replace('{music_content}', music_content)
        html_content = html_content.replace('{music_name}', music_name)
        
        return html_content
    except Exception as e:
        logger.error(f"生成HTML天气数据失败：{e}", exc_info=True)
        return f"生成天气数据失败：{e}"
